package com.chunxuan.langquan.ui.activity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.View;
import android.widget.CheckBox;
import android.widget.TextView;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.widget.AppCompatEditText;

import com.chunxuan.langquan.MainActivity;
import com.chunxuan.langquan.R;
import com.chunxuan.langquan.base.Base2Activity;
import com.chunxuan.langquan.base.BaseResult2;
import com.chunxuan.langquan.base.Config;
import com.chunxuan.langquan.base.Global;
import com.chunxuan.langquan.dao.bean.PwdLoginData;
import com.chunxuan.langquan.dao.bean.PwdLoginUserInfo;
import com.chunxuan.langquan.dao.bean.QqBean;
import com.chunxuan.langquan.dao.bean.QqloginBean;
import com.chunxuan.langquan.dao.bean.WxData;
import com.chunxuan.langquan.dao.bean.WxUserInfo;
import com.chunxuan.langquan.dao.bean.WxUserInfo1;
import com.chunxuan.langquan.dao.http.APIRetrofit;
import com.chunxuan.langquan.support.util.ActiviceCollector;
import com.chunxuan.langquan.support.util.AlertUtil;
import com.chunxuan.langquan.support.util.Logg;
import com.chunxuan.langquan.support.util.ShareUtils;
import com.google.gson.Gson;
import com.google.gson.internal.LinkedTreeMap;
import com.makeramen.roundedimageview.RoundedImageView;
import com.ruitu.arad.Arad;
import com.ruitu.arad.api.RxUtil;
import com.ruitu.arad.util.ToastUtils;
import com.tencent.connect.UserInfo;
import com.tencent.connect.auth.QQToken;
import com.tencent.connect.common.Constants;
import com.tencent.mm.opensdk.constants.ConstantsAPI;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.List;

import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;

public class LoginActivity extends Base2Activity {
    private AppCompatEditText et_phone,  et_pwd;// 手机号，密码
    private TextView tv_ok, tv_privacy_policy, tv_service_agreement,tv_forget_pwd,tv_regist;// 登录，隐私政策，协议条款,忘记密码
    private CheckBox cb_check;
    private RoundedImageView riWx,riQQ;
    private int LOGIN_TYPE = 0;// 0 普通登录 1 微信登录 2 QQ登录
    private WxUserInfo1 wxUserInfo1Bean;// 微信登录后解析的微信用户对象
    private WxUserInfo wxUserInfoBean;

    private QqBean qqBean;
    private QqloginBean qqloginBean;
    private static final String WX_APP_ID = Config.WX_APP_ID;

    private Tencent mTencent;
    private BaseUiListener mIUiListener;
    private UserInfo mUserInfo;


    // IWXAPI 是第三方app和微信通信的openApi接口
    private IWXAPI api;
    SendAuth.Req req;
    private AlertDialog alert;// 弹窗
    private View alert_view;
    private static final String ALERT_IS_FIRST = "ALERT_IS_FIRST";
    private void regToWx() {
        // 通过WXAPIFactory工厂，获取IWXAPI的实例
        api = WXAPIFactory.createWXAPI(this, WX_APP_ID, true);
        // 将应用的appId注册到微信
        api.registerApp(WX_APP_ID);
        //建议动态监听微信启动广播进行注册到微信
        registerReceiver(new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                // 将该app注册到微信
                api.registerApp(WX_APP_ID);
            }
        }, new IntentFilter(ConstantsAPI.ACTION_REFRESH_WXAPP));

    }
    private String phone,pwd;

    @Override
    protected int getLayoutRes() {
        return R.layout.activity_login;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ActiviceCollector.addActivity(this);
        //传入参数APPID和全局Context上下文
        mTencent = Tencent.createInstance(Config.QQ_APP_ID, LoginActivity.this);
        et_phone = findViewById(R.id.et_1);
        et_pwd = findViewById(R.id.et_2);
        tv_privacy_policy = findViewById(R.id.tv_privacy_policy);
        tv_service_agreement = findViewById(R.id.tv_service_agreement);
        tv_forget_pwd=findViewById(R.id.tv_forget_pwd);
        tv_regist=findViewById(R.id.tv_regist);
        riWx=findViewById(R.id.ri_wx);
        riQQ=findViewById(R.id.ri_qq);
        tv_ok = findViewById(R.id.tv_ok);
        cb_check = findViewById(R.id.cb_check);
        setHeadTitle("");
        setOnClickListener(tv_ok, tv_privacy_policy, tv_service_agreement,riWx,riQQ,tv_forget_pwd,tv_regist);
        regToWx();// 注册微信api
        req = new SendAuth.Req();
        alert = new AlertDialog.Builder(this, R.style.Dialog_FS).create();
        if(isFirst()){
            showDialog();
        }
    }
    //判断程序是否第一次运行
    private boolean isFirst() {
        boolean isFirst = ShareUtils.getBoolean(this, ALERT_IS_FIRST, true);
        if (isFirst) {
            ShareUtils.putBoolean(this, ALERT_IS_FIRST, false);
            //是第一次运行
            return true;
        } else {
            return false;
        }
    }
    public void showDialog() {// 弹窗
        alert.show();
        alert_view = View.inflate(this, R.layout.layout_alert_policy, null);
        alert.setMessage("");
        alert_view.findViewById(R.id.tv_user_policy).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(LoginActivity.this, UserAgreeActivity.class));
            }
        });
        alert_view.findViewById(R.id.tv_privacy).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(LoginActivity.this, PrivacyAgreeActivity.class));
            }
        });
        alert_view.findViewById(R.id.tv_1).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ShareUtils.putBoolean(LoginActivity.this, ALERT_IS_FIRST, true);
                alert.dismiss();
//                ActiviceCollector.finishAll();
            }
        });
        alert_view.findViewById(R.id.tv_2).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                alert.dismiss();
            }
        });

        AlertUtil.setAlertCenterStyle(alert.getWindow(), alert_view, this);
    }
    @Override
    protected void onResume() {
        super.onResume();
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
               boolean registBack= Arad.preferences.getBoolean("REGIST_BACK",false);
               if(!registBack){
                   LOGIN_TYPE=Arad.preferences.getInteger("LOGIN_TYPE", 0);
                   if(LOGIN_TYPE==1){
                       String wxUserInfo = Arad.preferences.getString("wxUserInfo");
                       String wxUserInfo1 = Arad.preferences.getString("wxUserInfo1");
                       Logg.e("==微信登录信息==" + wxUserInfo);
                       Logg.e("==微信登录信息111==" + wxUserInfo1);
                       if (!TextUtils.isEmpty(wxUserInfo)&&!TextUtils.isEmpty(wxUserInfo1)) {
                           Gson gson = new Gson();
                           wxUserInfoBean = gson.fromJson(wxUserInfo, WxUserInfo.class);
                           wxUserInfo1Bean = gson.fromJson(wxUserInfo1, WxUserInfo1.class);
                           Logg.e("==微信登录信息---666==" + wxUserInfoBean.toString());
                           Logg.e("==微信登录信息---7777==" + wxUserInfo1Bean.toString());
                           hideProgress();
                           reqWxLogin(wxUserInfoBean.getAccess_token(),wxUserInfoBean.getRefresh_token(),String.valueOf(wxUserInfoBean.getExpires_in()),
                                   wxUserInfoBean.getOpenid(),wxUserInfo1Bean.getNickname(),wxUserInfo1Bean.getHeadimgurl());
                           showProgress();
                       }
                   }else if(LOGIN_TYPE==2){
                       String qqUserInfo=Arad.preferences.getString("qqUserInfo");
                       String qqUserInfo1=Arad.preferences.getString("qqUserInfo1");
                       if(!TextUtils.isEmpty(qqUserInfo)&&!TextUtils.isEmpty(qqUserInfo1)){
                           Gson gson = new Gson();
                           qqBean=gson.fromJson(qqUserInfo,QqBean.class);
                           qqloginBean=gson.fromJson(qqUserInfo1,QqloginBean.class);
                           hideProgress();
                           reqQqLogin(qqBean.getAccess_token(),qqBean.getAccess_token(),String.valueOf(qqBean.getExpires_in()),
                                   qqBean.getOpenid(),qqloginBean.getNickname(),qqloginBean.getFigureurl_qq());
                           showProgress();
                       }
                   }
               }

            }
        }, 100);
    }

    @Override
    protected void onPause() {
        super.onPause();
        Arad.preferences.putBoolean("REGIST_BACK",false).flush();
    }

    //QQ登录
    private Disposable reqQqLogin(String access_token, String refresh_token, String expires_in, String openid, String nickName, String avatar) {
        return APIRetrofit.getDefault().qqLogin(access_token, refresh_token, expires_in, openid, nickName, avatar)
                .compose(RxUtil.<BaseResult2<WxData>>subIoObMain())
                .subscribe(new Consumer<BaseResult2<WxData>>() {
                    @Override
                    public void accept(BaseResult2<WxData> baseResult2) throws Exception {
                        hideProgress();
                        if (baseResult2.isSuccess()) {
                            Logg.e("==QQ登录== " + baseResult2);
                            Global.HEADER = baseResult2.getData().getUserinfo().getToken();
                            Arad.preferences.putString(Config.GLOBAL_HEADER, baseResult2.getData().getUserinfo().getToken()).flush();
                            Logg.e("==QQ登录--token== " + baseResult2.getData().getUserinfo().getToken());
                            String mobile=baseResult2.getData().getUserinfo().getMobile();
                            if(TextUtils.isEmpty(mobile)){
                                //未绑定手机号
                                startActivity(BindMobileActivity.class);
                            }else{
                                if(Global.IS_SHOW==1){
                                    startActivity(GuidActivity.class);
                                    finish();
                                }else if(Global.IS_SHOW==0){
                                    Intent intent=new Intent(LoginActivity.this, MainActivity.class);
                                    intent.putExtra("guid_id",0);
                                    startActivity(intent);
                                    finish();
                                }
                            }
//                            if(editGradeSuccess){
//                                if(Global.IS_SHOW==1){
//                                    startActivity(GuidActivity.class);
//                                    finish();
//                                }else if(Global.IS_SHOW==0){
//                                    Intent intent=new Intent(LoginActivity.this, MainActivity.class);
//                                    intent.putExtra("guid_id",0);
//                                    startActivity(intent);
//                                    finish();
//                                }
//                            }else{
//                                boolean registBack=Arad.preferences.getBoolean("REGIST_BACK",false);
//                                if(!registBack){
//                                    startActivity(RegistActivity.class);
//                                }
////                                finish();
//                            }
                        } else {
//                            if (TextUtils.equals("4001", baseResult2.getCode())) {// 注册成功,完善信息
//                                LinkedTreeMap<String, Integer> user = (LinkedTreeMap) baseResult2.getData();
//                                String tmp = user.get("id") + "";
//                                if (tmp.contains(".")) {
//                                    Global.USER_ID = tmp.substring(0, tmp.lastIndexOf("."));
//                                } else {
//                                    Global.USER_ID = tmp;
//                                }
//                                Logg.i("Global.USER_ID = " + Global.USER_ID);
//                                startActivity(RealAuthAgentActivity.class);
//                                LOGIN_TYPE = 0;// 登录类型设置为普通
//                            } else if (TextUtils.equals("4002", baseResult2.getCode())) {// 微信绑定手机号
//                                Bundle bundle = new Bundle();
//                                bundle.putSerializable("wxUserInfo", wxUserInfoBean);// 微信用户对象
//                                startActivity(BindPhoneActivity.class, bundle);
//                                LOGIN_TYPE = 0;// 登录类型设置为普通
//                            }
                        }
//                        ToastUtils.showShort(baseResult2.getMsg());
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        hideProgress();
                        throwable.printStackTrace();
                        ToastUtils.showShort("登录失败");
                    }
                });
    }
    // 微信登录
    private Disposable reqWxLogin(String access_token, String refresh_token, String expires_in, String openid, String nickName, String avatar) {
        return APIRetrofit.getDefault().wxLogin(access_token, refresh_token, expires_in, openid, nickName, avatar)
                .compose(RxUtil.<BaseResult2<WxData>>subIoObMain())
                .subscribe(new Consumer<BaseResult2<WxData>>() {
                    @Override
                    public void accept(BaseResult2<WxData> baseResult2) throws Exception {
                        hideProgress();
                        if (baseResult2.isSuccess()) {
                            Logg.e("==微信登录== " + baseResult2);
                            Global.HEADER = baseResult2.getData().getUserinfo().getToken();
                            Arad.preferences.putString(Config.GLOBAL_HEADER, baseResult2.getData().getUserinfo().getToken()).flush();
                            Logg.e("==微信登录--token== " + baseResult2.getData().getUserinfo().getToken());
                            String mobile=baseResult2.getData().getUserinfo().getMobile();
                            if(TextUtils.isEmpty(mobile)){
                                //未绑定手机号
                                startActivity(BindMobileActivity.class);
                            }else{
                                if(Global.IS_SHOW==1){
                                    startActivity(GuidActivity.class);
                                    finish();
                                }else if(Global.IS_SHOW==0){
                                    Intent intent=new Intent(LoginActivity.this, MainActivity.class);
                                    intent.putExtra("guid_id",0);
                                    startActivity(intent);
                                    finish();
                                }
                            }
                        } else {
//                            if (TextUtils.equals("4001", baseResult2.getCode())) {// 注册成功,完善信息
//                                LinkedTreeMap<String, Integer> user = (LinkedTreeMap) baseResult2.getData();
//                                String tmp = user.get("id") + "";
//                                if (tmp.contains(".")) {
//                                    Global.USER_ID = tmp.substring(0, tmp.lastIndexOf("."));
//                                } else {
//                                    Global.USER_ID = tmp;
//                                }
//                                Logg.i("Global.USER_ID = " + Global.USER_ID);
//                                startActivity(RealAuthAgentActivity.class);
//                                LOGIN_TYPE = 0;// 登录类型设置为普通
//                            } else if (TextUtils.equals("4002", baseResult2.getCode())) {// 微信绑定手机号
//                                Bundle bundle = new Bundle();
//                                bundle.putSerializable("wxUserInfo", wxUserInfoBean);// 微信用户对象
//                                startActivity(BindPhoneActivity.class, bundle);
//                                LOGIN_TYPE = 0;// 登录类型设置为普通
//                            }
                        }
//                        ToastUtils.showShort(baseResult2.getMsg());
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        hideProgress();
                        throwable.printStackTrace();
                        ToastUtils.showShort("登录失败");
                    }
                });
    }
    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()){
            case R.id.tv_forget_pwd:
                Intent intent=new Intent(LoginActivity.this,ResetPwdActivity.class);
                startActivity(intent);
                break;
            case R.id.tv_regist:
                Intent intent1=new Intent(LoginActivity.this,RegistActivity.class);
                startActivity(intent1);
                break;
            case R.id.tv_ok:
                phone = et_phone.getText().toString().trim();
                pwd = et_pwd.getText().toString().trim();
                if (TextUtils.isEmpty(phone)) {
                    ToastUtils.showShort("请输入手机号");
                    return;
                }
                if (TextUtils.isEmpty(pwd)) {
                    ToastUtils.showShort("请输入密码");
                    return;
                }
                 if (!cb_check.isChecked()) {
                    ToastUtils.showShort("请阅读并同意《服务协议》和《隐私政策》");
                    return;
                }
                login();
                showProgress();
                break;
            case R.id.tv_privacy_policy:
                startActivity(PrivacyAgreeActivity.class);
                break;
            case R.id.tv_service_agreement:
                startActivity(UserAgreeActivity.class);
                break;
            case R.id.ri_wx:
                if(!api.isWXAppInstalled()){
                    ToastUtils.showShort("您还未安装微信客户端");
                    return;
                }
                LOGIN_TYPE = 1;// 登录类型设置为微信
                Arad.preferences.putInteger("LOGIN_TYPE", LOGIN_TYPE).flush();
                req.scope = "snsapi_userinfo,snsapi_friend,snsapi_message,snsapi_contact";
                req.state = "none";
                api.sendReq(req);
                break;
            case R.id.ri_qq:
/**通过这句代码，SDK实现了QQ的登录，这个方法有三个参数，第一个参数是context上下文，第二个参数SCOPO 是一个String类型的字符串，表示一些权限
 官方文档中的说明：应用需要获得哪些API的权限，由“，”分隔。例如：SCOPE = “get_user_info,add_t”；所有权限用“all”
 第三个参数，是一个事件监听器，IUiListener接口的实例，这里用的是该接口的实现类 */
                mIUiListener = new BaseUiListener();
                //all表示获取所有权限
                mTencent.login(LoginActivity.this,"all", mIUiListener);
                LOGIN_TYPE = 2;// 登录类型设置为QQ
                Arad.preferences.putInteger("LOGIN_TYPE", LOGIN_TYPE).flush();
                break;

        }
    }
    /**
     * 自定义监听器实现IUiListener接口后，需要实现的3个方法
     * onComplete完成 onError错误 onCancel取消
     */
    private class BaseUiListener implements IUiListener {

        @Override
        public void onComplete(Object response) {
            ToastUtils.showShort("授权成功");
            Logg.e("====QQ====" + response);
            Arad.preferences.putString("qqUserInfo", response.toString()).flush();
            JSONObject obj = (JSONObject) response;
            try {
                String openID = obj.getString("openid");
                String accessToken = obj.getString("access_token");
                String expires = obj.getString("expires_in");
                mTencent.setOpenId(openID);
                mTencent.setAccessToken(accessToken,expires);
                QQToken qqToken = mTencent.getQQToken();
                mUserInfo = new UserInfo(getApplicationContext(),qqToken);
                mUserInfo.getUserInfo(new IUiListener() {
                    @Override
                    public void onComplete(Object response) {
                        Logg.e("==登录成功=="+response.toString());
                        Arad.preferences.putString("qqUserInfo1", response.toString()).flush();
                        String qqUserInfo=Arad.preferences.getString("qqUserInfo");
                        String qqUserInfo1=Arad.preferences.getString("qqUserInfo1");
                        if(!TextUtils.isEmpty(qqUserInfo)&&!TextUtils.isEmpty(qqUserInfo1)){
                            Gson gson = new Gson();
                            qqBean=gson.fromJson(qqUserInfo,QqBean.class);
                            qqloginBean=gson.fromJson(qqUserInfo1,QqloginBean.class);
                            hideProgress();
                            reqQqLogin(qqBean.getAccess_token(),qqBean.getAccess_token(),String.valueOf(qqBean.getExpires_in()),
                                    qqBean.getOpenid(),qqloginBean.getNickname(),qqloginBean.getFigureurl_qq());
                            showProgress();
                        }
                    }

                    @Override
                    public void onError(UiError uiError) {
                        Logg.e("==登录失败=="+uiError.toString());
                    }

                    @Override
                    public void onCancel() {
                        Logg.e("==登录取消==");

                    }

                    @Override
                    public void onWarning(int i) {

                    }
                });
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onError(UiError uiError) {
            ToastUtils.showShort("授权失败");
        }
        @Override
        public void onCancel() {
            ToastUtils.showShort("授权取消");
        }
        @Override
        public void onWarning(int i) {
        }
    }
    /**
     * 在调用Login的Activity或者Fragment中重写onActivityResult方法
     * @param requestCode
     * @param resultCode
     * @param data
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if(requestCode == Constants.REQUEST_LOGIN){
            Tencent.onActivityResultData(requestCode,resultCode,data,mIUiListener);
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    public Disposable login() {
        return APIRetrofit.getDefault().login(phone, pwd)
                .compose(RxUtil.<BaseResult2<PwdLoginData>>subIoObMain())
                .subscribe(new Consumer<BaseResult2<PwdLoginData>>() {
                    @Override
                    public void accept(BaseResult2<PwdLoginData> baseResult2) throws Exception {
                        hideProgress();
                        Logg.e("==密码登录== " + baseResult2);
                        if (baseResult2.isSuccess()) {
                            ToastUtils.showShort(baseResult2.getMsg());
                            Arad.preferences.putString(Config.USER_PREF_KEY, phone).flush();
                            Arad.preferences.putString(Config.PASSWORD_PREF_KEY, pwd).flush();
                            Global.HEADER=baseResult2.getData().getUserinfo().getToken();
                            Arad.preferences.putString(Config.GLOBAL_HEADER, baseResult2.getData().getUserinfo().getToken()).flush();
                            Logg.e("==请求头== " + Global.HEADER);
                            if(Global.IS_SHOW==1){
                                Intent intent=new Intent(LoginActivity.this,GuidActivity.class);
                                startActivity(intent);
                                finish();
                            }else if(Global.IS_SHOW==0){
                                Intent intent=new Intent(LoginActivity.this, MainActivity.class);
                                intent.putExtra("guid_id",0);
                                startActivity(intent);
                                finish();
                            }
                        } else {
                            ToastUtils.showShort(baseResult2.getMsg());
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        hideProgress();
                        throwable.printStackTrace();
                        ToastUtils.showShort("登录失败，请重试");
                    }
                });
    }

}
